package com.putao.album.album;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.putao.album.R;
import com.putao.album.album.bean.PhotoGridItem;
import com.putao.album.album.view.GridImageView;
import com.putao.album.album.view.GridImageView.OnMeasureListener;
import com.putao.album.fileupload.FileUploadDBHelper;
import com.putao.album.util.BitmapHelper;
import com.putao.album.util.CommonUtils;
import com.putao.album.util.DateUtil;
import com.putao.album.util.StringHelper;
import com.putao.album.util.UmengTouchEvent;
import com.putao.album.widget.stickygridheaders.StickyGridHeadersSimpleAdapter;
import com.umeng.analytics.MobclickAgent;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class AlbumGridAdapter extends BaseAdapter implements StickyGridHeadersSimpleAdapter {

    private List<PhotoGridItem> list;
    private LayoutInflater mInflater;
    private GridView mGridView;
    private Point mPoint = new Point(0, 0);
    private boolean isMultiSelect;
    private Context mContext;
    private UpdateCallback callback;

    public AlbumGridAdapter(Context context, List<PhotoGridItem> list, GridView mGridView, UpdateCallback callback) {
        mContext = context;
        this.list = list;
        mInflater = LayoutInflater.from(context);
        this.mGridView = mGridView;
        this.callback = callback;
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder mViewHolder;
        String path = list.get(position).getPath();

        if (convertView == null) {
            mViewHolder = new ViewHolder();
            convertView = mInflater.inflate(R.layout.layout_album_select_grid_item, parent, false);
            mViewHolder.mImageView = (GridImageView) convertView.findViewById(R.id.grid_item);
            mViewHolder.mSelectView = (ImageView) convertView.findViewById(R.id.selector_album);
            mViewHolder.selected_background = (View) convertView.findViewById(R.id.selected_background);
            mViewHolder.upload_success_tv = (TextView) convertView.findViewById(R.id.upload_success_tv);
            convertView.setTag(mViewHolder);

            mViewHolder.mImageView.setOnMeasureListener(new OnMeasureListener() {

                @Override
                public void onMeasureSize(int width, int height) {
                    mPoint.set(width, height);
                }
            });

        } else {
            mViewHolder = (ViewHolder) convertView.getTag();
        }

        if (isMultiSelect) {
            mViewHolder.mSelectView.setVisibility(View.VISIBLE);
            if (list.get(position).isSelected()) {
                mViewHolder.mSelectView.setSelected(true);
                mViewHolder.selected_background.setVisibility(View.VISIBLE);
            } else {
                mViewHolder.mSelectView.setSelected(false);
                mViewHolder.selected_background.setVisibility(View.INVISIBLE);
            }

            if (FileUploadDBHelper.getInstance().isUploadSuccess(CommonUtils.getBabyId(), path)) {
                mViewHolder.selected_background.setVisibility(View.VISIBLE);
                mViewHolder.upload_success_tv.setVisibility(View.VISIBLE);
            } else {
                mViewHolder.upload_success_tv.setVisibility(View.INVISIBLE);
            }

        } else {
            mViewHolder.mSelectView.setVisibility(View.INVISIBLE);
        }

        mViewHolder.mImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        mViewHolder.mImageView.setTag(path);
        if (ActivityAlbumPhotoSelect.IS_CAMERA_ICON.equals(path)) {
            DisplayImageOptions options = new DisplayImageOptions.Builder()
                    .showImageForEmptyUri(new BitmapDrawable(mContext.getResources(), getCameraIon()))
                    .cacheInMemory(true).cacheOnDisk(true).bitmapConfig(Bitmap.Config.RGB_565)
                    .build();
            ImageLoader.getInstance().displayImage(null, mViewHolder.mImageView, options);
            mViewHolder.mImageView.setVisibility(View.VISIBLE);
            mViewHolder.mSelectView.setVisibility(View.INVISIBLE);
        } else {
            DisplayImageOptions options = new DisplayImageOptions.Builder()
                    .showImageOnLoading(BitmapHelper.getLoadingDrawable()).showImageOnFail(BitmapHelper.getLoadingDrawable())
                    .cacheInMemory(true).bitmapConfig(Bitmap.Config.RGB_565)
                    .considerExifParams(true)
                    .build();
            ImageLoader.getInstance().displayImage("file://" + path, mViewHolder.mImageView, options);
        }
        return convertView;
    }

    private Bitmap getCameraIon() {
        int with = 240;
        int height = 240;
        Bitmap bitmap = Bitmap.createBitmap(with, height, Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);
        Paint paint = new Paint();
        paint.setFlags(Paint.FILTER_BITMAP_FLAG);
        canvas.drawColor(0xffffffff);
        Bitmap bmp = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.album_camera_icon);
        canvas.drawBitmap(bmp, (with - bmp.getWidth()) / 2, (height - bmp.getHeight()) / 2, paint);
        return bitmap;
    }

    @Override
    public View getHeaderView(final int position, View convertView, ViewGroup parent) {
        HeaderViewHolder mHeaderHolder;
        if (convertView == null) {
            mHeaderHolder = new HeaderViewHolder();
            convertView = mInflater.inflate(R.layout.layout_album_select_item_header, parent, false);
            mHeaderHolder.tv_day = (TextView) convertView.findViewById(R.id.day_tv);
            mHeaderHolder.tv_week = (TextView) convertView.findViewById(R.id.week_tv);
            mHeaderHolder.select_all = (TextView) convertView.findViewById(R.id.select_all);
            convertView.setTag(mHeaderHolder);
        } else {
            mHeaderHolder = (HeaderViewHolder) convertView.getTag();
        }
        String date_str = list.get(position).getTime();
        if (!StringHelper.isEmpty(date_str)) {
            // int month = DateUtil.getMonth(DateUtil.getDate(date_str));
            // int day = DateUtil.getDay(DateUtil.getDate(date_str));
            String week = DateUtil.getWeekSting(DateUtil.getDate(date_str));

            String curdate = new SimpleDateFormat(mContext.getResources().getString(R.string.time_format_year_month_day)).format(new Date(System.currentTimeMillis()));
            if (date_str.startsWith(curdate)) {
                mHeaderHolder.tv_day.setText("今天");
                mHeaderHolder.tv_week.setText(" " + date_str + " (" + week + ")");
            } else {
                mHeaderHolder.tv_day.setText(date_str);
                mHeaderHolder.tv_week.setText(" (" + week + ")");
            }
        }

        if (isMultiSelect) {
            mHeaderHolder.select_all.setVisibility(View.VISIBLE);
        } else {
            mHeaderHolder.select_all.setVisibility(View.INVISIBLE);
        }

        final long headId = getHeaderId(position);
        final boolean sectionSelected = list.get(position).isSectionSelected();
        if (sectionSelected) {
            mHeaderHolder.select_all.setText(mContext.getString(R.string.select_all_cancle));
        } else {
            mHeaderHolder.select_all.setText(mContext.getString(R.string.select_all));
        }

        //判断是否只有相机Icon
        boolean only_camera_item = true;
        for (int i = 0; i < list.size(); i++) {
            PhotoGridItem item = list.get(i);
            if (item.getSection() == headId) {
                if (!item.getPath().contains("isCamera")) {
                    only_camera_item = false;
                    break;
                }
            }
        }

        if (only_camera_item) {
            mHeaderHolder.select_all.setTextColor(mContext.getResources().getColor(R.color.grey_light));
            mHeaderHolder.select_all.setClickable(false);
        } else {
            mHeaderHolder.select_all.setTextColor(mContext.getResources().getColor(R.color.blue));
            mHeaderHolder.select_all.setClickable(true);

        }
        mHeaderHolder.select_all.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean need_update = false;

                // Loger.d("chen+++select_all.setOnClickListener()++position()=" + position + ",headId=" + headId);
                if (!sectionSelected) {
                    MobclickAgent.onEvent(mContext, UmengTouchEvent.CLICK_SELECTALL);
                }
                for (int i = 0; i < list.size(); i++) {
                    PhotoGridItem item = list.get(i);
                    if (item.getSection() == headId) {

                        if (sectionSelected) {
                            item.setSelected(false);
                            item.setSectionSelected(false);
                            need_update = true;
                        } else {
                            if (callback.getSelectNum() >= ActivityAlbumPhotoSelect.MAX_SELECTED) {
                                Toast.makeText(mContext, mContext.getResources().getString(R.string.select_all_to_max), Toast.LENGTH_SHORT).show();
                                break;
                            }
                            if (item.getPath().contains("isCamera")||(FileUploadDBHelper.getInstance().isUploadSuccess(CommonUtils.getBabyId(), item.getPath()))) {
                                item.setSelected(false);
                            } else {
                                item.setSelected(true);
                            }
                            item.setSectionSelected(true);
                            need_update = true;
                        }
                    }
                }
                if (need_update) {
                    callback.updateTextView();
                    notifyDataSetChanged();
                }
            }
        });
        return convertView;
    }

    public static class ViewHolder {
        public View selected_background;
        public GridImageView mImageView;
        public ImageView mSelectView;
        public TextView upload_success_tv;
    }

    public static class HeaderViewHolder {
        public TextView tv_day;
        public TextView tv_week;
        public TextView select_all;
    }

    @Override
    public long getHeaderId(int position) {
        return list.get(position).getSection();
    }

    public void setMultiSelect(boolean isMultiSelect) {
        this.isMultiSelect = isMultiSelect;
//        notifyDataSetChanged();
    }

    public interface UpdateCallback {
        public void updateTextView();

        public int getSelectNum();
    }

}
